package com.xiaohua.web.core.config;

import com.xiaohua.common.config.RuoYiConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;

import java.util.ArrayList;
import java.util.List;

// 恢复这些必要的导入
import springfox.documentation.service.RequestParameter;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.schema.ScalarType;

// 添加必要的导入
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.service.ParameterType;
import org.springframework.http.MediaType;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

/**
 * Swagger2的接口配置
 *
 * @author ruoyi
 */
@Configuration
@EnableKnife4j
public class SwaggerConfig
{
    /** 系统基础配置 */
    @Autowired
    private RuoYiConfig ruoyiConfig;

    /** 是否开启swagger */
    @Value("${swagger.enabled}")
    private boolean enabled;

    /** 设置请求的统一前缀 */
    @Value("${swagger.pathMapping}")
    private String pathMapping;
    
    /**
     * Knife4j扩展配置
     */
    @Autowired
    private OpenApiExtensionResolver openApiExtensionResolver;

    /**
     * 创建API分组，包含所有接口
     */
    @Bean
    public Docket createRestApi()
    {
        // 设置支持的媒体类型
        Set<String> contentTypes = new HashSet<>();
        contentTypes.add(MediaType.APPLICATION_JSON_VALUE);
        contentTypes.add(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        contentTypes.add(MediaType.MULTIPART_FORM_DATA_VALUE);
        
        return new Docket(DocumentationType.OAS_30)
                // 是否启用Swagger
                .enable(enabled)
                // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
                .apiInfo(apiInfo())
                // 分组名称
                .groupName("所有接口")
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api，用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 不过滤任何路径，显示所有API
                .paths(PathSelectors.any())
                .build()
                /* 设置安全模式，swagger可以设置访问token */
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .pathMapping(pathMapping)
                .useDefaultResponseMessages(false)
                // 设置支持的媒体类型
                .consumes(contentTypes)
                .produces(contentTypes)
                // 指定要忽略的参数类型，但不忽略MultipartFile
                .ignoredParameterTypes(HttpServletRequest.class, HttpServletResponse.class, HttpSession.class)
                // 添加增强配置，但不添加全局文件参数
                .extensions(openApiExtensionResolver.buildExtensions("图文魔方"))
                // 添加对文件上传的支持
                .globalRequestParameters(Arrays.asList(
                    new RequestParameterBuilder()
                        .name("files")
                        .description("文件上传")
                        .in(ParameterType.FORM)
                        .required(false)
                        .build()
                ));
    }

    /**
     * 安全模式，这里指定token通过Authorization头请求头传递
     */
    private List<SecurityScheme> securitySchemes()
    {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts()
    {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .operationSelector(o -> o.requestMappingPattern().matches("/.*") 
                            // 排除登录注册相关接口，使这些接口不需要Authorization
                            && !o.requestMappingPattern().matches("/(login|register).*")
                            && !o.requestMappingPattern().matches("/captchaImage")
                            && !o.requestMappingPattern().contains("/login-username")
                            && !o.requestMappingPattern().contains("/register-username")
                            && !o.requestMappingPattern().contains("/login-mobile")
                            && !o.requestMappingPattern().contains("/register-mobile")
                            && !o.requestMappingPattern().contains("/send-code")
                            && !o.requestMappingPattern().contains("/wechat-login"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth()
    {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题：图文魔方_接口文档")
                // 描述
                .description("描述：图文魔方的后端管理面板，用于管理图文魔方的各项功能。\n" +
                        "接口文档地址：http://localhost:8080/doc.html#/home")
                // 作者信息
                .contact(new Contact(ruoyiConfig.getName(), "http://localhost:8080/doc.html#/home", null))
                // 版本
                .version("版本号:" + ruoyiConfig.getVersion())
                .build();
    }
}
